package org.txazo.blog.commons.prop;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import org.txazo.blog.util.StringUtil;

/**
 * 类路径Properties
 * 
 * @author Tu XiaoZhou
 * @since 2013-10-21
 * 
 */
public class ClassPathProperties implements Properties {

	private String file;

	public ClassPathProperties(String file) {
		this.file = file;
	}

	@Override
	public Map<String, String> load() {
		if (StringUtil.isEmpty(file)) {
			return null;
		}

		if (!file.startsWith("/")) {
			file = "/" + file;
		}

		Map<String, String> map = new HashMap<String, String>();
		InputStream in = this.getClass().getResourceAsStream(file);
		if (in != null) {
			java.util.Properties prop = new java.util.Properties();
			try {
				prop.load(in);
				Enumeration<Object> keys = prop.keys();
				while (keys.hasMoreElements()) {
					String key = (String) keys.nextElement();
					map.put(key, prop.getProperty(key));
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (in != null) {
					try {
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return map;
	}

}
